package com.project.school_flate.util.wechat;

import com.project.school_flate.util.DateUtils;
import com.project.school_flate.util.system.ComVariableUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author
 * @Date 2024/4/10 11:08
 * @Version v1.0.0
 * @Message 微信推送消息
 **/
@Component
@Slf4j
public class WxMessagesManager {

    /**
     * 推送模板
     * @param openId 接收者openid
     * @param map 模板数据
     * @return
     * @throws Exception
     */
    public void pushWxMessages(String openId, Map<String,String> map) throws Exception {
        String templateId = "kGZknIbZS_dymrUBJfKxI8OToNM2CeJg39l1gQI1n6Q";
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(ComVariableUtil.getSystemValue("wx_appid"));
        wxStorage.setSecret(ComVariableUtil.getSystemValue("wx_secret"));
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        // 此处的 key/value 需和模板消息对应
        List<WxMpTemplateData> wxMpTemplateDataList = Arrays.asList(
                new WxMpTemplateData("thing2", map.get("type"), "#FF0000"),
                new WxMpTemplateData("character_string10", map.get("oOrderTakeawayId")),
                new WxMpTemplateData("thing16", map.get("state")),
                new WxMpTemplateData("thing11", map.get("content")),
                new WxMpTemplateData("time4", DateUtils.dateTurnString(new Date(),"yyyy年MM月dd日 HH:mm"))
        );
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId) // openId为1.3步骤中得到的微信号
                .templateId(templateId)
                .data(wxMpTemplateDataList)
                .url("http://fanshanming.top/")  // 跳转详情地址
                .build();
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            log.info("消息模版发送成功~");
        } catch (Exception e) {
            log.error("推送失败：" + e.getMessage());
        }
    }

}

